<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">纵向课题</span>
        <span style="color: #8c8c8c; line-height: 7vh; font-size: 0.8rem; font-weight: bold;">相关文件：立项书、任务书等。</span>
      </div>

      <pdf-preview :pdf-url="ruleForm.pdfUrl" @update:pdf-path="updatepdfUrl"></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; display: flex;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">信息详情</span>
          <span style="line-height: 7vh; margin-left: 3vh; color: #CACACA; font-weight: bold">带<span style="color: red;"> * </span>号为必填项</span>
        </div>

        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="120px" style="margin-top: 5vh">
            <el-form-item label="课题名称" prop="projectName" required>
              <el-input v-model="ruleForm.projectName" placeholder="请填写课题名称" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="基金名称" prop="fundName" required>
              <el-input v-model="ruleForm.fundName" placeholder="如：国家自然科学基金" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="课题类型" prop="projectType">
              <el-select v-model="ruleForm.projectType" placeholder="请选择课题类型" style="width: 34vw;">
                <el-option label="---请选择---" value=""></el-option>
                <el-option label="重点" value="重点"></el-option>
                <el-option label="面上" value="面上"></el-option>
                <el-option label="青年" value="青年"></el-option>
                <el-option label="一般" value="一般"></el-option>
                <el-option label="自筹" value="自筹"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="授予单位" prop="grantingUnit">
              <el-input v-model="ruleForm.grantingUnit" placeholder="请填写授予单位" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="课题级别" prop="projectLevel" required>
              <el-select v-model="ruleForm.projectLevel" placeholder="请选择课题级别" style="width: 34vw;">
                <el-option label="国家级" value="国家级"></el-option>
                <el-option label="省部级" value="省部级"></el-option>
                <el-option label="市厅级" value="市厅级"></el-option>
                <el-option label="校级" value="校级"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="课题编号" prop="projectNumber" >
              <el-input v-model="ruleForm.projectNumber" placeholder="请填写课题编号" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="到账经费(万)" prop="fundingAmount" >
              <el-input-number
                  v-model="ruleForm.fundingAmount"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 34vw;"
                  placeholder="请输入到账经费金额">
              </el-input-number>
            </el-form-item>

            <el-form-item label="本人排名" prop="rank" required>
              <el-select v-model="ruleForm.rank" placeholder="请选择排名" style="width: 34vw;">
                <el-option
                    v-for="i in 13"
                    :key="i"
                    :label="`第${i}名`"
                    :value="i">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开始时间" prop="startTime" required>
              <el-date-picker
                  v-model="ruleForm.startTime"
                  type="date"
                  placeholder="选择开始日期"
                  style="width: 34vw;"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" prop="endTime" required>
              <el-date-picker
                  v-model="ruleForm.endTime"
                  type="date"
                  placeholder="选择结束日期"
                  style="width: 34vw;"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="课题状态" prop="projectStatus" required>
              <el-select v-model="ruleForm.projectStatus" placeholder="请选择课题状态" style="width: 34vw;">
                <el-option label="在研" value="在研"></el-option>
                <el-option label="结题" value="结题"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto;">
                <ul style="display: flex; list-style-type: none; padding: 0; margin: 0; line-height: 6vh; color: #3f3f3f">
                  <li style="margin-left: 1.5vw">排序</li>
                  <li style="margin-left: 3vw">姓名</li>
                  <li style="margin-left: 3.5vw">作者身份</li>
                  <li style="margin-left: 5vw">单位名称</li>
                </ul>
                <div v-for="(author, index) in ruleForm.authorInfo" :key="index" style="margin-top: 1vh; display: flex; align-items: center;">
                  <el-select style="width: 4vw;" v-model="author.rank" placeholder="排名">
                    <el-option
                        v-for="i in 13"
                        :key="i"
                        :label="i"
                        :value="i">
                    </el-option>
                  </el-select>
                  <el-input v-model="author.name" style="width: 5vw; margin-left: 1vw" placeholder="姓名"></el-input>
                  <el-select style="width: 5.5vw; margin-left: 1vw" v-model="author.identity" placeholder="身份">
                    <el-option
                        v-for="item in identityOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input
                      placeholder="单位名称"
                      v-model="author.institution"
                      style="width: 15vw; margin-left: 3vw">
                  </el-input>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="备注信息" prop="remarks">
              <el-input
                  type="textarea"
                  :rows="4"
                  v-model="ruleForm.remarks"
                  placeholder="请输入备注信息"
                  style="width: 34vw;">
              </el-input>
            </el-form-item>
          </el-form>

          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submit" class="submit-button">返 回</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import PdfPreview from "@/components/result/PdfPreview.vue"
import { getLongitudinalProjects } from "@/api/result/longitudinalProjects.js"

const router = useRouter()
const route = useRoute()
const ruleFormRef = ref(null)

const ruleForm = reactive({
  id: '',
  projectName: '',
  fundName: '',
  projectType: '',
  grantingUnit: '',
  projectLevel: '',
  projectNumber: '',
  fundingAmount: null,
  rank: null,
  startTime: '',
  endTime: '',
  projectStatus: '',
  remarks: '',
  pdfUrl: '',
  authorInfo: [{
    rank: 1,
    name: '',
    identity: '',
    institution: ''
  }]
})

const identityOptions = [
  { value: '老师', label: '老师' },
  { value: '博士生', label: '博士生' },
  { value: '硕士生', label: '硕士生' },
  { value: '本科生', label: '本科生' },
  { value: '其他', label: '其他' }
]

const rules = reactive({
  projectName: [{ required: true, message: '请输入课题名称', trigger: 'blur' }],
  fundName: [{ required: true, message: '请输入基金名称', trigger: 'blur' }],
  projectLevel: [{ required: true, message: '请选择课题级别', trigger: 'change' }],
  rank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
})

const addAuthor = () => {
  ruleForm.authorInfo.push({
    rank: ruleForm.authorInfo.length + 1,
    name: '',
    identity: '',
    institution: ''
  })
}

const removeAuthor = (index) => {
  ruleForm.authorInfo.splice(index, 1)
}

const updatepdfUrl = (newPath) => {
  ruleForm.pdfUrl = newPath
}

const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 安全转换日期为字符串格式（YYYY-MM-DD）
const parseDateToString = (dateValue) => {
  if (!dateValue) return '';

  // 处理时间戳（数字类型）
  if (typeof dateValue === 'number') {
    return formatDate(dateValue);
  }

  // 处理字符串格式日期（如"2025-08-13"或时间戳字符串）
  if (typeof dateValue === 'string') {
    // 尝试转换为数字（如果是时间戳字符串）
    const numValue = Number(dateValue);
    if (!isNaN(numValue)) {
      return formatDate(numValue);
    }
    // 直接返回字符串格式日期（如果已符合YYYY-MM-DD）
    return dateValue;
  }

  return '';
}

const submit = async () => {
  router.push("/result/longitudinalProjects");
}

onMounted(async () => {
  const longitudinalId = route.query.id
  if (longitudinalId) {
    try {
      const res = await getLongitudinalProjects(longitudinalId)
      if (res.code === 200 && res.data) {
        const data = res.data
        // 修复时间显示问题：使用安全转换函数处理日期
        data.startTime = parseDateToString(data.startTime);
        data.endTime = parseDateToString(data.endTime);
        Object.assign(ruleForm, data)
      } else {
        ElMessage.error('获取纵向课题信息失败')
      }
    } catch (error) {
      console.error('获取纵向课题信息出错:', error)
      ElMessage.error('获取纵向课题信息失败，请重试')
    }
  }
})
</script>

<style scoped>
.submit-button {
  color: white;
  height: 3.8vh;
  width: 10vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
  border-radius: 4px;
}

.submit-button:hover {
  background-color: #009b77;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select .el-input__inner) {
  text-align: left;
}
</style>
